package ar.cpfw.hibernate.mapping.main;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import ar.cpfw.hibernate.mapping.onetomany.Department;
import ar.cpfw.hibernate.mapping.onetomany.Employee;
import ar.cpfw.hibernate.mapping.onetoone.Angus;
import ar.cpfw.hibernate.mapping.onetoone.Malcolm;
import ar.cpfw.hibernate.mapping.valueobjects.Address;
import ar.cpfw.hibernate.mapping.valueobjects.Person;
import ar.cpfw.hibernate.mapping.valueobjects.Phone;


public class XMLHibernate {

	public static void main(String args[]) {
		Configuration configuration = new Configuration().configure();
		
		StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
				.applySettings(configuration.getProperties());
		
		ServiceRegistry serviceRegistry = builder.build();
		
		SessionFactory factory = configuration.buildSessionFactory(serviceRegistry);

		Session session = factory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			
			// one-to-one, sharing PK
			Angus angus = new Angus();
			Malcolm malcolm = new Malcolm();
			malcolm.setAngus(angus);
			angus.setMalcolm(malcolm);
			session.save(angus);

			//one to many... for bidirectional use many-to-one from the other end
			Department angus3 = new Department();
			Employee malcolm3 = new Employee();
			Employee malcolm3_1 = new Employee();
			angus3.addEmployee(malcolm3);
			angus3.addEmployee(malcolm3_1);
			malcolm3.setDepartment(angus3);
			malcolm3_1.setDepartment(angus3);
			session.save(angus3);
			
			//one to many, Collections of Strings and Collections of Value Objects... 
			Person aPerson = new Person();
			aPerson.addColour("blue");
			aPerson.addColour("red");
			Phone aPhone = new Phone("aNumber");
			aPerson.addPhone(aPhone);
			Address anAddress = new Address("anAddress");
			aPerson.setAddress(anAddress);
			session.save(aPerson);

			
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
			factory.close();
		}
	}
	
}
